package com.arithmetic;

/**
 * 风险的猪（计算你能获得的最大收益）
 * 
 * @author Administrator
 * 
 */
public class Solution {

	/**
	 * 计算你能获得的最大收益（股票收益）
	 * @param prices Prices[i]即第i天的股价
	 * @return 整型
	 */
	public static int calculateMax(int[] prices) {
		int[] lprofit = new int[prices.length];// 存放max{第一次卖出-第一次买入｝
		int[] rprofit = new int[prices.length];// 存放max｛第二次持有最高值-第二次买入｝

		// 从左到右循环
		int maxProfit = 0;// 计算已有的最大收益
		int minPrice = prices[0];// 已经获得的最小值
		for (int i = 0; i < prices.length; i++) {
			if (minPrice > prices[i]) {
				minPrice = prices[i];
			}
			if (maxProfit < (prices[i] - minPrice)) {// 最大值产生比较
				maxProfit = (prices[i] - minPrice);
			}
			lprofit[i] = maxProfit;
		}
		// 从右到左循环
		maxProfit = 0;
		rprofit[prices.length - 1] = 0;
		int maxPrice = prices[prices.length - 1];
		minPrice = prices[prices.length - 1];
		int temp;
		for (int j = (prices.length - 2); j >= 0; j--) {
			if (maxPrice < prices[j]) {
				maxPrice = prices[j];
			}
			if (maxProfit < (temp = maxPrice - prices[j])) {
				maxProfit = temp;
			}
			rprofit[j] = maxProfit;
		}
		// 计算总和
		maxProfit = 0;
		for (int i = 0; i < prices.length; i++) {
			if ((temp = lprofit[i] + rprofit[i]) > maxProfit) {
				maxProfit = temp;
			}

		}
		return maxProfit;
	}
	
	public static void main(String[] args) {
		int p[] = {3,8,5,1,7,8};
		
		System.out.println(calculateMax(p));
	}
}